package com.netstar.salesman_90dsp.activity;

import java.util.Date;

import org.apache.http.Header;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;

import roboguice.inject.InjectView;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.netstar.salesman_90dsp.R;
import com.netstar.salesman_90dsp.TitleBaseActivity;
import com.netstar.salesman_90dsp.config.WebServerConfig;
import com.netstar.salesman_90dsp.engine.ToadayWorkAddEngine;
import com.netstar.salesman_90dsp.model.CommonResponseModel;
import com.netstar.salesman_90dsp.model.TodayWorkModel;
import com.netstar.salesman_90dsp.tool.DialogTool;
import com.squareup.timessquare.CalendarPickerView.OnDateSelectedListener;

/**
 * 今日工作，添加页面
 * 
 * @author zhangshuai
 * 
 */
public class TodayWorkAddActivity extends TitleBaseActivity {
	/**
	 * 工作请求回调类
	 */
	private PublishHttpHandler getToadyWorkHttpHandler;
	/**
	 * 今日工作业务逻辑类
	 */
	private ToadayWorkAddEngine toadayWorkAddEngine;
	/**
	 * 时间
	 */
	@InjectView(R.id.activity_today_work_add_tv_date)
	TextView activity_today_work_add_tv_date;
	/**
	 * 工作内容
	 */
	@InjectView(R.id.activity_today_work_add_et_content)
	EditText activity_today_work_add_et_content;
	/**
	 * 要新增，或者要修改的工作model
	 */
	private TodayWorkModel todayWorkModel;
	/**
	 * 最小日期
	 */
	private DateTime dateTimeMin = DateTime.now().minusYears(2);
	/**
	 * 最大日期
	 */
	private DateTime dateTimeMax = DateTime.now().plusYears(2);
	/**
	 * 当前日期
	 */
	private DateTime dateTimeCurrent = DateTime.now();

	/**
	 * 传过来的日期
	 */

	@Override
	public void subInitContentView(Bundle savedInstanceState) {
		setContentView(R.layout.activity_today_work_add);
	}

	@Override
	public void subInitView() {
		// 设置title
		include_title_tv_activity_name.setVisibility(View.VISIBLE);
		include_title_tv_activity_name
				.setText(R.string.activity_today_work_title_add);
		include_title_bt_right.setVisibility(View.VISIBLE);
		include_title_bt_left.setVisibility(View.VISIBLE);
		include_title_bt_left.setText(R.string.common_text_back);
		include_title_bt_right.setText(R.string.common_text_save);
		// 日期放入txtview，尽行显示
		activity_today_work_add_tv_date
				.setText(dateTimeCurrent.toString(getResources().getString(
						R.string.common_format_date)));
		// 日期dialog
		dateChooseDialog = dialogTool.getDateChooseDialog(
				R.layout.activity_today_work_dialog_date_choose,
				DialogTool.VIEW_ID_CALENDAR);
		// 设置标题
		((TextView) (dateChooseDialog.resLayoutView
				.findViewById(R.id.include_title_tv_activity_name_little)))
				.setText(R.string.common_text_choose_date);
		// 隐藏左右按钮
		dateChooseDialog.resLayoutView.findViewById(
				R.id.include_title_bt_left_little).setVisibility(View.GONE);
		dateChooseDialog.resLayoutView.findViewById(
				R.id.include_title_bt_right_little).setVisibility(View.GONE);
		// 初始化日期时间
		dateChooseDialog.calendarPickerView.init(dateTimeMin.toDate(),
				dateTimeMax.toDate());
		dateChooseDialog.calendarPickerView
				.selectDate(dateTimeCurrent.toDate());
		dateChooseDialog.calendarPickerView
				.setOnDateSelectedListener(new OnDateSelectedListener() {
					DateTime selectDate = null;

					@Override
					public void onDateUnselected(Date date) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onDateSelected(Date date) {
						selectDate = new DateTime(date);
						// 设置时间，回传使用
						todayWorkModel.setPlanDate(selectDate
								.toString(getResources().getString(
										R.string.common_format_date_time)));
						// 展示使用
						activity_today_work_add_tv_date.setText(selectDate
								.toString(getResources().getString(
										R.string.common_format_date)));
						dateChooseDialog.dismiss();
					}
				});
	}

	@Override
	public void subInitParam() {
		toadayWorkAddEngine = new ToadayWorkAddEngine(activityContext);
		getToadyWorkHttpHandler = new PublishHttpHandler();
		// 接收传过来的数据
		if (getIntent() != null
				&& getIntent().hasExtra(TodayWorkModel.INTENT_KEY)) {
			todayWorkModel = getIntent().getParcelableExtra(
					TodayWorkModel.INTENT_KEY);
			// 内容
			activity_today_work_add_et_content.setText(todayWorkModel
					.getPlans());
		} else {
			todayWorkModel = new TodayWorkModel();
			// 将今天的日期放入日期控件
			activity_today_work_add_tv_date.setText(new LocalDate()
					.toString("yyyy-MM-dd"));
		}
		// 新添加的必须写 0
		todayWorkModel.setId("0");
		// 状态都为未完成
		todayWorkModel.setState("0");
	}

	@Override
	public void subSetOnclick() {
		setOnclickWithDefaultListener(include_title_bt_left);
		setOnclickWithDefaultListener(include_title_bt_right);
		setOnclickWithDefaultListener(activity_today_work_add_tv_date);
	}

	@Override
	public void subRunSomeThing() {

	}

	@Override
	public void callbackWithDefaultListener(View view) {
		super.callbackWithDefaultListener(view);
		switch (view.getId()) {
		case R.id.include_title_bt_left:
			// 返回按钮
			finish();
			break;
		case R.id.include_title_bt_right:
			// 保存按钮
			startPublish();
			break;
		case R.id.activity_today_work_add_tv_date:
			// 时间选择
			dateChooseDialog.show();
			break;

		default:
			break;
		}
	}

	/**
	 * 开始发表工作做
	 */
	private void startPublish() {
		// 开启等待框
		waittingAlertDialog = dialogTool.getWaittingDialog(-1, getResources()
				.getString(R.string.common_string_Loading));
		waittingAlertDialog.show();

		// 验证数据
		if (TextUtils
				.isEmpty(getStringFromView(activity_today_work_add_et_content))) {
			endPublish(
					false,
					getResources().getString(
							R.string.common_string_not_allow_null));
		} else {
			// 设置工作内容
			todayWorkModel
					.setPlans(getStringFromView(activity_today_work_add_et_content));
			// 设置时间
			todayWorkModel.setPlanDate(activity_today_work_add_tv_date
					.getText().toString());
			// 通过网络获取数据
/*			asyncHttpClient.post(
					WebServerConfig.getUrl(WebServerConfig.TodayWorkAddAction),
					toadayWorkAddEngine.getRequestParams(todayWorkModel),
					getToadyWorkHttpHandler);*/
		}
	}

	/**
	 * 获取结束
	 */
	public void endPublish(boolean isSuccess, String msg) {
		// 取消登录框
		if (waittingAlertDialog != null) {
			waittingAlertDialog.dismiss();
			waittingAlertDialog = null;
		}
		if (isSuccess) {
			// 发表成功，退到列表界面
			finish();
		} else {
			// 失败
			msg = TextUtils.isEmpty(msg) ? getResources().getString(
					R.string.common_string_unknown_mistake) : msg;
			Toast.makeText(activityContext, msg, Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 工作请求回调类
	 * 
	 * @author zhangshuai
	 * 
	 */
	private class PublishHttpHandler extends
			BaseJsonHttpResponseHandler<CommonResponseModel> {
		private String errorMsg;

		@Override
		public void onFailure(int arg0, Header[] arg1, Throwable arg2,
				String arg3, CommonResponseModel arg4) {
			errorMsg = null;
			errorMsg = getStringFromThrowable(arg2);
			endPublish(false, errorMsg);
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, String arg2,
				CommonResponseModel arg3) {
			errorMsg = null;
			// 成功，不仅是网络请求成功，也得是验证成功，才是成功
			if (arg3 != null && arg3.isResult()) {
				endPublish(true, null);
			} else {
				// 表示返回异常，不成功
				endPublish(false, null);
			}
		}

		@Override
		protected CommonResponseModel parseResponse(String arg0)
				throws Throwable {
			return new ObjectMapper().readValues(
					new JsonFactory().createParser(arg0.substring(1,
							arg0.length() - 1)), CommonResponseModel.class)
					.next();

		}

	}

}
